package com.bcu.wish.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.bcu.wish.config.GlobalConfig;
import com.bcu.wish.entity.Message;
import com.bcu.wish.entity.Userinfo;
import com.bcu.wish.entity.search.UserSearch;
import com.bcu.wish.mapper.UserinfoMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.bcu.wish.mapper.UserMapper;
import com.bcu.wish.entity.User;
import com.bcu.wish.service.UserService;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserinfoMapper userinfoMapper;

    @Resource
    private GlobalConfig globalConfig;

    @Override
    public Message adminLogin(String userId, String userPwd) {
        User user = userMapper.selectByUserIdAndUserPwd(userId, userPwd);
        if (user==null){
            return Message.fail("帐号密码错误");
        }else{
            return Message.success(null).add(user);
        }




    }

    @Override
    public int deleteByPrimaryKey(String userId) {
        return userMapper.deleteByPrimaryKey(userId);
    }

    @Override
    public Message insert(User record) {
        return Message.success(null).add(userMapper.insert(record));
    }

    @Override
    public Message insertSelective(User record) {

        return userMapper.insertSelective(record) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public Message selectByPrimaryKey(String userId) {
        return Message.success(null).add(userMapper.selectByPrimaryKey(userId));
    }

    @Override
    public int updateByPrimaryKeySelective(User record) {
        return userMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(User record) {
        return userMapper.updateByPrimaryKey(record);
    }

    @Override
    public Message login(String userId, String userPwd) {

        User user = userMapper.selectByUserIdAndUserPwd(userId, userPwd);

        if (user != null) {
            // 用户已存在，则直接返回其信息
            Userinfo userinfo = new Userinfo();
            Userinfo userinfo2 = userinfoMapper.selectByPrimaryKey(userId);

            userinfo.setUserinfoTestScore(userinfo2.getUserinfoTestScore());
            userinfo.setUserinfoUserName(userinfo2.getUserinfoUserName());
            userinfo.setUserinfoUserIdcard(userinfo2.getUserinfoUserIdcard());
            userinfo.setUserinfoUserId(userinfo2.getUserinfoUserId());
            user.setUserinfo(userinfo);
            return Message.success(null).add(user);
        } else {
            //用户表中无该用户，于userinfo表中查询
            Userinfo userinfo = userinfoMapper.selectByUserinfoUserIdAndUserinfoUserIdcard(userId, userPwd);
            if (userinfo != null) {
                User u = new User();
                u.setUserId(userId);
                u.setUserPwd(userPwd);
                u.setUserType(0);
                return Message.success(null).add(userMapper.insert(u));
            } else {
                return Message.fail("用户名或密码错误");
            }
        }
    }

    @Override
    public Message selectUserResultByUserId(String userId) {
        return Message.success(null).add(userMapper.selectUserResultByUserId(userId));
    }

    @Override
    public Message selectAll() {
        return Message.success(null).add(userMapper.selectAll());
    }

    @Override
    public Message selectByUserType(Integer userType) {
        return Message.success(null).add(userMapper.selectByUserType(userType));
    }

    @Override
    public Message getExcel2() {
        ArrayList rows = new ArrayList<>();
        List<User> Englishusers = userMapper.selectUserResultOrderByScore("英语");
        int xuhao=1;
        for (int i=0;i<Englishusers.size();i++)
        {
            User user = Englishusers.get(i);
            Map<String,Object> row =new LinkedHashMap<>();
            row.put("序号",xuhao);
            xuhao++;
            row.put("学号",user.getUserId());
            row.put("姓名",user.getUserinfo().getUserinfoUserName());
            row.put("身份证号",user.getUserinfo().getUserinfoUserIdcard());
            row.put("入学英语测试成绩（总分）",user.getUserinfo().getUserinfoTestScore());
            row.put("词汇题(单项分数）",user.getUserinfo().getUserinfoCihuiScore());
            row.put("语法题(单项分数）",user.getUserinfo().getUserinfoYufaScore());
            row.put("完形填空题（单项分数）",user.getUserinfo().getUserinfoWanxingScore());
            row.put("阅读理解题（单项分数）",user.getUserinfo().getUserinfoReadScore());
            row.put("系统中的最终录取结果",user.getUserResult());
            row.put("第一志愿",user.getWishfill().getWishFirst());
            row.put("第二志愿",user.getWishfill().getWishSecond());
            row.put("第三志愿",user.getWishfill().getWishThird());
            row.put("第四志愿",user.getWishfill().getWishFourth());
            row.put("第五志愿",user.getWishfill().getWishFifth());
            row.put("备注","");
            rows.add(row);
        }



        List<User> Tranusers = userMapper.selectUserResultOrderByScore("翻译");

        for (int i=0;i<Tranusers.size();i++)
        {
            User user = Tranusers.get(i);
            Map<String,Object> row =new LinkedHashMap<>();
            row.put("序号",xuhao);
            xuhao++;
            row.put("学号",user.getUserId());
            row.put("姓名",user.getUserinfo().getUserinfoUserName());
            row.put("身份证号",user.getUserinfo().getUserinfoUserIdcard());
            row.put("入学英语测试成绩（总分）",user.getUserinfo().getUserinfoTestScore());
            row.put("词汇题(单项分数）",user.getUserinfo().getUserinfoCihuiScore());
            row.put("语法题(单项分数）",user.getUserinfo().getUserinfoYufaScore());
            row.put("完形填空题（单项分数）",user.getUserinfo().getUserinfoWanxingScore());
            row.put("阅读理解题（单项分数）",user.getUserinfo().getUserinfoReadScore());
            row.put("系统中的最终录取结果",user.getUserResult());
            row.put("第一志愿",user.getWishfill().getWishFirst());
            row.put("第二志愿",user.getWishfill().getWishSecond());
            row.put("第三志愿",user.getWishfill().getWishThird());
            row.put("第四志愿",user.getWishfill().getWishFourth());
            row.put("第五志愿",user.getWishfill().getWishFifth());
            row.put("备注","");
            rows.add(row);
        }
        List<User> Gusers = userMapper.selectUserResultOrderByScore("德语");

        for (int i=0;i<Gusers.size();i++)
        {
            User user = Gusers.get(i);
            Map<String,Object> row =new LinkedHashMap<>();
            row.put("序号",xuhao);
            xuhao++;
            row.put("学号",user.getUserId());
            row.put("姓名",user.getUserinfo().getUserinfoUserName());
            row.put("身份证号",user.getUserinfo().getUserinfoUserIdcard());
            row.put("入学英语测试成绩（总分）",user.getUserinfo().getUserinfoTestScore());
            row.put("词汇题(单项分数）",user.getUserinfo().getUserinfoCihuiScore());
            row.put("语法题(单项分数）",user.getUserinfo().getUserinfoYufaScore());
            row.put("完形填空题（单项分数）",user.getUserinfo().getUserinfoWanxingScore());
            row.put("阅读理解题（单项分数）",user.getUserinfo().getUserinfoReadScore());
            row.put("系统中的最终录取结果",user.getUserResult());
            row.put("第一志愿",user.getWishfill().getWishFirst());
            row.put("第二志愿",user.getWishfill().getWishSecond());
            row.put("第三志愿",user.getWishfill().getWishThird());
            row.put("第四志愿",user.getWishfill().getWishFourth());
            row.put("第五志愿",user.getWishfill().getWishFifth());
            row.put("备注","");
            rows.add(row);
        }

        List<User> Fusers = userMapper.selectUserResultOrderByScore("法语");

        for (int i=0;i<Fusers.size();i++)
        {
            User user = Fusers.get(i);
            Map<String,Object> row =new LinkedHashMap<>();
            row.put("序号",xuhao);
            xuhao++;
            row.put("学号",user.getUserId());
            row.put("姓名",user.getUserinfo().getUserinfoUserName());
            row.put("身份证号",user.getUserinfo().getUserinfoUserIdcard());
            row.put("入学英语测试成绩（总分）",user.getUserinfo().getUserinfoTestScore());
            row.put("词汇题(单项分数）",user.getUserinfo().getUserinfoCihuiScore());
            row.put("语法题(单项分数）",user.getUserinfo().getUserinfoYufaScore());
            row.put("完形填空题（单项分数）",user.getUserinfo().getUserinfoWanxingScore());
            row.put("阅读理解题（单项分数）",user.getUserinfo().getUserinfoReadScore());
            row.put("系统中的最终录取结果",user.getUserResult());
            row.put("第一志愿",user.getWishfill().getWishFirst());
            row.put("第二志愿",user.getWishfill().getWishSecond());
            row.put("第三志愿",user.getWishfill().getWishThird());
            row.put("第四志愿",user.getWishfill().getWishFourth());
            row.put("第五志愿",user.getWishfill().getWishFifth());
            row.put("备注","");
            rows.add(row);
        }

        List<User> Spainusers = userMapper.selectUserResultOrderByScore("西语");

        for (int i=0;i<Spainusers.size();i++)
        {
            User user = Spainusers.get(i);
            Map<String,Object> row =new LinkedHashMap<>();
            row.put("序号",xuhao);
            xuhao++;
            row.put("学号",user.getUserId());
            row.put("姓名",user.getUserinfo().getUserinfoUserName());
            row.put("身份证号",user.getUserinfo().getUserinfoUserIdcard());
            row.put("入学英语测试成绩（总分）",user.getUserinfo().getUserinfoTestScore());
            row.put("词汇题(单项分数）",user.getUserinfo().getUserinfoCihuiScore());
            row.put("语法题(单项分数）",user.getUserinfo().getUserinfoYufaScore());
            row.put("完形填空题（单项分数）",user.getUserinfo().getUserinfoWanxingScore());
            row.put("阅读理解题（单项分数）",user.getUserinfo().getUserinfoReadScore());
            row.put("系统中的最终录取结果",user.getUserResult());
            row.put("第一志愿",user.getWishfill().getWishFirst());
            row.put("第二志愿",user.getWishfill().getWishSecond());
            row.put("第三志愿",user.getWishfill().getWishThird());
            row.put("第四志愿",user.getWishfill().getWishFourth());
            row.put("第五志愿",user.getWishfill().getWishFifth());
            row.put("备注","");
            rows.add(row);
        }




        ArrayList<Map<String,Object>> allrows = CollUtil.newArrayList(rows);
        // 通过工具类创建writer
        System.out.println(globalConfig.filePath);
        ExcelWriter writer = ExcelUtil.getWriter(globalConfig.filePath+"result2.xlsx");
        // 合并单元格后的标题行，使用默认标题样式
        //writer.merge(rows.size() - 1, "志愿填报");
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(allrows, true);
        // 关闭writer，释放内存
        writer.close();
        String returnUrl=globalConfig.hostUrl+"resource/"+"result2.xlsx";

        return Message.success(null).add(returnUrl);
    }



    @Override
    public Message getExcel() {
       ArrayList rows = new ArrayList<>();
        List<User> Englishusers = userMapper.selectUserResultOrderByScore("英语");

        for (int i=0;i<Englishusers.size();i++)
        {
            User user = Englishusers.get(i);
            Map<String,Object> row =new LinkedHashMap<>();
            row.put("学号",user.getUserId());
            row.put("学生姓名",user.getUserinfo().getUserinfoUserName());
            row.put("录取专业",user.getUserResult());
            if (user.getUserinfo().getUserinfoRemarks()!=null){
                row.put("成绩是否一致",user.getUserinfo().getUserinfoRemarks());
            }
            else row.put("成绩是否一致","否");
            rows.add(row);
       }



        List<User> Tranusers = userMapper.selectUserResultOrderByScore("翻译");

        for (int i=0;i<Tranusers.size();i++)
        {
            User user = Tranusers.get(i);
            Map<String,Object> row =new LinkedHashMap<>();
            row.put("学号",user.getUserId());
            row.put("学生姓名",user.getUserinfo().getUserinfoUserName());
            row.put("录取专业",user.getUserResult());
            if (user.getUserinfo().getUserinfoRemarks()!=null){
                row.put("成绩是否一致",user.getUserinfo().getUserinfoRemarks());
            }
            else row.put("成绩是否一致","否");
            rows.add(row);
        }
        List<User> Gusers = userMapper.selectUserResultOrderByScore("德语");

        for (int i=0;i<Gusers.size();i++)
        {
            User user = Gusers.get(i);
            Map<String,Object> row =new LinkedHashMap<>();
            row.put("学号",user.getUserId());
            row.put("学生姓名",user.getUserinfo().getUserinfoUserName());
            row.put("录取专业",user.getUserResult());
            if (user.getUserinfo().getUserinfoRemarks()!=null){
                row.put("成绩是否一致",user.getUserinfo().getUserinfoRemarks());
            }
            else row.put("成绩是否一致","否");
            rows.add(row);
        }

        List<User> Fusers = userMapper.selectUserResultOrderByScore("法语");

        for (int i=0;i<Fusers.size();i++)
        {
            User user = Fusers.get(i);
            Map<String,Object> row =new LinkedHashMap<>();
            row.put("学号",user.getUserId());
            row.put("学生姓名",user.getUserinfo().getUserinfoUserName());
            row.put("录取专业",user.getUserResult());
            if (user.getUserinfo().getUserinfoRemarks()!=null){
                row.put("成绩是否一致",user.getUserinfo().getUserinfoRemarks());
            }
            else row.put("成绩是否一致","否");
            rows.add(row);
        }

        List<User> Spainusers = userMapper.selectUserResultOrderByScore("西语");

        for (int i=0;i<Spainusers.size();i++)
        {
            User user = Spainusers.get(i);
            Map<String,Object> row =new LinkedHashMap<>();
            row.put("学号",user.getUserId());
            row.put("学生姓名",user.getUserinfo().getUserinfoUserName());
            row.put("录取专业",user.getUserResult());
            if (user.getUserinfo().getUserinfoRemarks()!=null){
                row.put("成绩是否一致",user.getUserinfo().getUserinfoRemarks());
            }
            else row.put("成绩是否一致","否");
            rows.add(row);
        }




        ArrayList<Map<String,Object>> allrows = CollUtil.newArrayList(rows);
        // 通过工具类创建writer
        System.out.println(globalConfig.filePath);
        ExcelWriter writer = ExcelUtil.getWriter(globalConfig.filePath+"result.xlsx");
        // 合并单元格后的标题行，使用默认标题样式
        //writer.merge(rows.size() - 1, "志愿填报");
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(allrows, true);
        // 关闭writer，释放内存
        writer.close();
        String returnUrl=globalConfig.hostUrl+"resource/"+"result.xlsx";

        return Message.success(null).add(returnUrl);
    }

    @Override
    public Message updateUserResultByUserId(String userId, String userResult) {
        return Message.success(null).add(userMapper.updateUserResultByUserId(userId, userResult));
    }

    @Override
    public Message resetPassword(String userId) {
        User user = userMapper.selectByPrimaryKey(userId);

        if (user != null) {
            String idCard = user.getUserinfo().getUserinfoUserIdcard();
            String newPwd = idCard.substring(idCard.length() - 6);
            return Message.success(null).add(userMapper.updateUserPwdByUserId(userId, newPwd));
        } else {
            return Message.fail("用户不存在");
        }
    }

    @Override
    public Message changePwd(String userId, String userPwd) {
        return userMapper.updateUserPwdByUserId(userId, userPwd)>0?Message.success(null):Message.fail(null);
    }

    @Override
    public Message search(UserSearch user) {
        return Message.success(null).add(userMapper.search(user));
    }


}


